<template>
  <el-input v-model="input" placeholder="Please input" />
  <el-input v-model="uid" placeholder="Please input" />
  <el-button type="primary" @click="connect">连接socket</el-button>
  <u-chat :user-id="userId" :emoji="emoji" :data="data" @submit="submit"></u-chat>
 </template>
 <script setup lang="ts">
 import { onMounted, reactive, ref } from 'vue'
import { ChatApi, ChatSubmitParam } from 'undraw-ui'
import emoji from '../../assets/emoji'
const userId = ref(1)
const input = ref('0000')
const uid = ref('0000')
const data = reactive<ChatApi[]>([
  { id: 1, username: 'user', avatar: '', content: 'adfsdfa' },
])

const submit = ({ clear, content }) => {
  data.push({ id: 1, username: 'user', avatar: '', content: content })
  clear()
  let sendData = {
    type:'send_to_uid',
    uid:uid.value,
    message:content
  }
  socket.send(JSON.stringify(sendData))
}



let socket: WebSocket
const open =()=>{
  console.log('open')
}
const connect = () => {
  console.log('执行了')
  console.log(input.value)
  const address = `ws://43.139.15.245:8282?token=${input.value}`
  if (window.WebSocket) {
    socket = new WebSocket(address)
    //相当于channelRead0，ev收到服务器端回送的消息
    socket.onmessage = ev => {
      console.log(ev.data)
      let jsonObj = JSON.parse(ev.data);
      if(jsonObj.type == 'send_to_uid'){
        data.push(jsonObj.content)
        botton()
      }
    }
    // 连接开启
    socket.onopen = ev => {
      console.log('连接开启了...')
    }
    // 感知到连接关闭
    socket.onclose = ev => {
      console.log('连接关闭了...')
    }
  } else {
    alert('当前的浏览器不支持webSocket')
  }
}

const send = () => {
  if (socket.readyState == WebSocket.OPEN) {
    //通过socket 发送消息
    socket.send('你好呀!')
  }
}
const botton =()=>{
  // const questionCardDom = document.getElementById("questionCard");
  const boxes = document.getElementsByClassName("self");
  if (boxes) {
    for (var i = 0; i < boxes.length; i++) {
      console.log('1')
    boxes[i].scrollTop = boxes[i].scrollHeight;
}
  }
}
// onMounted(() => {
//   connect()
// })
 </script>
 <style scoped lang="scss">
 
 </style>